use async_trait::async_trait;
use base_data::channel::EndReason;
use tools::ResultNull;
use tracing::info;

use crate::{
	business::{
		bus_trait::Business,
		inbound400::context::{BusinessState, InboundRunContext},
	},
	config::business_config,
	db::persistence::InboundDBO,
	link_to_sip::play_sound_file_to_caller,
	CallingLogType,
};

#[derive(Debug, Clone)]
pub struct NotTurnNumFound;

#[async_trait]
impl Business for NotTurnNumFound {
	type C = InboundRunContext;

	async fn play_back_stop(&self, context: &mut InboundRunContext,_channel_id:u32) -> ResultNull {
		context.business_state = BusinessState::End(EndReason::NotSetNumber);

		Ok(())
	}

	async fn hangup(
		&self,
		context: &mut Self::C,
		_channel_id: u32,
		_reason: EndReason
	) -> ResultNull {
				info!("未设置号码流程,收到挂断消息");
		context.business_state = BusinessState::End(EndReason::NotSetNumber);

		Ok(())
	}

	async fn start_call(&self, context: &mut InboundRunContext) -> ResultNull {
		//根据情况，给新node设置播放彩铃，并且给一个值。用来修改呼叫记录，因为到这里已经进行了一次呼叫记录了
		//如果有被叫， 而进到这里，则是没有获取被叫。只有一种可能就是所有被叫都时间段限制了。
		let (calling_type, bell_path) = if InboundDBO::node_has_phone(&context.target()).await? {
			(EndReason::NoAllowTimeCaller, business_config().time_refuse)
		} else {
			(EndReason::NotSetNumber, business_config().not_phone_node)
		};

		//进行修改呼叫记录的callin_type
		InboundDBO::record_calling_log(
			context,
			CallingLogType::GiveACall,
			calling_type,
			None,
			Some(context.node_info.node_id),
			&context.call_start_time,
			crate::business::TurnnumCallType::Unknow,
		)
		.await?;

		play_sound_file_to_caller(&context.caller_channel(), bell_path)?;

		Ok(())
	}
}
